package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Register;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author eneko_lana
 *
 */
/**
 * implementation of RegisterDAOInterface
 * @author VB
 *
 */
public class RegisterDAO implements RegisterDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public RegisterDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one Register by Id
	 * @param id
	 * @return Register
	 */
	 @Transactional(readOnly = true)
	public Register selectById(int id) {
		 Register Register = (Register) getSession().get(Register.class, id);
	    return Register;
	}

	/*
	 * retrieves all Registers from db
	 * @return List of Registers
	 */
	 @Transactional(readOnly = true)
	 public List<Register> selectAll() {
	 
	    List<Register> Registers = getSession().createQuery("from register").list();
	    return Registers;
	}
	
	/*
	 * retrieves all Registers from db
	 * @return List of Registers
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Register> Registers = getSession().createQuery("from register").list();
	    return Registers.size();
	}

	/*
	 * inserts a new Register in database
	 * retrieves generated id and sets to Register instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Register Register) {
	    Integer id = (Integer) getSession().save(Register);
	    Register.setId(id);           
	}

	/*
	 * updates Register
	 * @param Register to update
	 */
	 @Transactional
	public void update(Register Register) {
		getSession().merge(Register);
	}

	/*
	 * delete given Register
	 * @param Register to delete
	 */
	 @Transactional
	public void delete(Register Register) {
		getSession().delete(Register);
	}

	 @Transactional
	public void saveOrUpdate(Register Register) {

		getSession().saveOrUpdate(Register);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Register Register = (Register) getSession().load(Register.class,id);
		 getSession().delete(Register);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Register> search(String name) {
		   Query query = getSession().createQuery("from register s where s.name like :name");
           query.setParameter("name", "%"+name+"%");
           
           List<Register> names = query.list();
		
           return names;
	}

}
